<template>
  <div class="app-container">
    <!-- 原有的随销收入内容 -->
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="区县" prop="district">
        <el-select
          v-model="queryParams.district"
          clearable
          placeholder="请选择区县"
          @change="handleCountyChange"
          style="width: 120px"
        >
          <el-option
            v-for="c in countyOptions"
            :key="c"
            :label="c"
            :value="c"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="网格名称" prop="gridName">
        <el-select
          v-model="queryParams.gridName"
          clearable
          placeholder="请选择网格名称"
          style="width: 220px"
        >
          <el-option
            v-for="grid in gridOptions"
            :key="grid"
            :label="grid"
            :value="grid"
          />
        </el-select>
      </el-form-item> -->

      <!-- <el-form-item label="代维姓名" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入代维姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item> -->
      <el-form-item label="考核时间" prop="time">
        <el-date-picker
          style="width: 140px"
          v-model="queryParams.time"
          clearable
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          placeholder="请选择考核时间"
          :default-value="getDefaultMonth()"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <!-- 其他表单项... -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button
          v-hasPermi="['system:income:edit']"
          type="primary"
          icon="Upload"
          :disabled="single"
          @click="handleUpdate"
          >导入</el-button
        > -->
        <div style="margin-right: 10px">
          <input
            ref="fileInput"
            type="file"
            accept=".xlsx, .xls"
            style="display: none"
            @change="handleFileChangeAndImport"
          />

          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:order:export']"
            >导出</el-button
          >
          <div v-if="selectedFile" style="margin-top: 5px; color: #666">
            已选文件：{{ selectedFile.name }}
          </div>
        </div>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          v-hasPermi="['system:income:remove']"
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        > -->
      </el-col>
      <!-- <right-toolbar :show-search="showSearch" @queryTable="getList" /> -->
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="incomeList"
      border
      :resizable="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="区县" align="center" prop="district" /> -->
      <el-table-column label="区县" align="center" prop="district">
        <template #default="scope">
          {{ formatDistrictName(scope.row.district)|| scope.row.district || '未知' }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="渠道ID"
        align="center"
        prop="channelId"
        width="90"
      />
      <el-table-column
        label="渠道名称"
        align="center"
        prop="channelName"
        width="150"
      /> -->
      <!-- <el-table-column label="网格ID" align="center" prop="gridId" /> -->
      <el-table-column
        label="网格名称"
        align="center"
        prop="by1"
        width="130"
      />
      <el-table-column
        label="代维ID"
        align="center"
        prop="maintainerId"
        width="95"
      />
      <el-table-column label="代维姓名" align="center" prop="realName" />
      <!-- <el-table-column label="手机号" align="center" prop="phone" width="113" /> -->
      <el-table-column label="家客小计" align="center" prop="homeSubtotal" />
      <el-table-column label="企客小计" align="center" prop="bizSubtotal" />
      <el-table-column label="激励总额" align="center" prop="totalSalary" />
      <el-table-column label="随销/新装占比" align="center" prop="ratio" />
      <el-table-column
        label="考核时间"
        align="center"
        prop="ofTime"
        width="100"
      />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="handlePagination"
    />
  </div>
</template>

<script>
import { delsalaryIncome } from "@/api/dwxc/salary.js";
import {
  listIncome,
  getGridName,
  importIncomeData,
  uploadFile,
  getSalaryOver50perByMonth
} from "@/api/dwxc/income";
import { parseTime } from "@/utils/ruoyi";
import Pagination from "@/components/Pagination";
import SparkMD5 from "spark-md5";
import { download} from "@/utils/request";
// import RightToolbar from "@/components/RightPanel";
import { listCounty } from "@/api/dwxc/information";

export default {
  name: "Income",
  components: {
    Pagination,
    // RightToolbar,
  },
  data() {
    return {
      incomeList: [],
      total: 0,
      loading: true,
      showSearch: true,
      single: false,
      multiple: false,
      gridOptions: [], // 新增网格选项
      countyOptions: [],
      // 区县名称映射表（显示名称 -> 接口参数名称）
      districtNameMap: {
        全市: "全市",
        浔阳区: "浔阳",
        濂溪区: "濂溪",
        柴桑区: "柴桑",
        瑞昌市: "瑞昌",
        共青城: "共青",
        庐山市: "庐山",
        武宁县: "武宁",
        修水县: "修水",
        永修县: "永修",
        德安县: "德安",
        都昌县: "都昌",
        湖口县: "湖口",
        彭泽县: "彭泽",
      },
      // 反向映射表（接口参数名称 -> 显示名称）
      reverseDistrictNameMap: {
        全市: "全市",
        浔阳: "浔阳区",
        濂溪: "濂溪区",
        柴桑: "柴桑区",
        瑞昌: "瑞昌市",
        共青: "共青城",
        庐山: "庐山市",
        武宁: "武宁县",
        修水: "修水县",
        永修: "永修县",
        德安: "德安县",
        都昌: "都昌县",
        湖口: "湖口县",
        彭泽: "彭泽县",
      },
      gridMap: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        district: "全市",
        gridName: "",
        time: this.getLastMonth(), // 修改为动态获取上个月
      },
      selectedRows: [],
      // 导入文件列表，避免重复导入
      importedFiles: [],
      selectedFileHash: null, // 记录当前选择文件的哈希值
      uploadedFileHashes: [], // 记录已上传过的文件哈希值
      uploadedFilePath: null, // ✅ 使用 res.fileName
    };
  },
  created() {
    console.log('初始化查询参数:', this.queryParams);
    this.getList();
    this.getCountyList(); // 添加区县列表获取
  },
  methods: {
    // 添加获取区县列表的方法
    getCountyList() {
      listCounty().then(res => {
        // 根据实际返回的数据结构进行处理
        // 直接返回了数组，而不是 {code: 200, data: [...]} 的结构
        if (Array.isArray(res)) {
          this.countyOptions = res;
        } else if (res && res.code === 200 && Array.isArray(res.data)) {
          // 如果是标准的 {code: 200, data: [...]} 格式
          this.countyOptions = res.data;
        } else {
          console.error("无效的区县数据格式:", res);
          this.$message.error("获取区县列表失败: 数据格式错误");
        }
      }).catch(error => {
        console.error("获取区县列表失败:", error);
        this.$message.error("获取区县列表失败");
      });
    },
    // 获取上个月的年月字符串
      getLastMonth() {
        const now = new Date();
        now.setMonth(now.getMonth() - 1);
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      },
      
      // 获取默认月份（用于el-date-picker的:default-value）
      getDefaultMonth() {
        const lastMonth = this.getLastMonth();
        return new Date(lastMonth + '-01');
      },

    handleExport() {
      // 创建导出参数，排除分页参数
      const exportParams = {...this.queryParams};
      delete exportParams.pageNum;
      delete exportParams.pageSize;
      
      // 处理区县参数映射（与查询时保持一致）
      if (exportParams.district && this.districtNameMap[exportParams.district]) {
        exportParams.district = this.districtNameMap[exportParams.district];
      }
      
      // 添加ofTime参数，值为考核时间
      exportParams.ofTime = exportParams.time;
      delete exportParams.time;
      
      download('/maintainerSalary/salaryOver50perByMonthExport', exportParams, 
        `随销达标率数据_${new Date().getTime()}.xlsx`)
    },
    handleDelete() {
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }

      const ids = this.selectedRows.map((row) => row.id); // 假设数据中有 id 字段
      console.log("准备删除的 ids:", ids);

      this.$confirm("是否确认删除选中的数据项?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("调用 delsalaryIncome");
          delsalaryIncome(ids)
            .then((res) => {
              console.log("删除结果:", res);
              if (res.code === 200) {
                this.$message.success("删除成功");
                this.getList(); // 刷新列表
              } else {
                this.$message.error(res.msg || "删除失败");
              }
            })
            .catch((err) => {
              this.$message.error("请求失败");
              console.error("删除失败:", err);
            });
        })
        .catch(() => {
          // 取消操作
        });
    },
    handleFileChangeAndImport(fileEvent) {
      const file = fileEvent.target.files[0];
      if (!file) return;

      this.selectedFile = file;
      this.$message.info("已选择文件: " + file.name);

      // 生成文件哈希值
      const reader = new FileReader();
      reader.onload = (e) => {
        const spark = new SparkMD5.ArrayBuffer();
        spark.append(e.target.result);
        const fileHash = spark.end();
        this.selectedFileHash = fileHash;

        // 检查是否已上传过该文件
        if (this.uploadedFileHashes.includes(fileHash)) {
          this.$message.warning("该文件内容已上传过，请勿重复上传");
          return;
        }

        // 开始上传
        this.uploadFileAndImport();
      };
      reader.readAsArrayBuffer(file);
    },

    // 上传文件并导入数据
    uploadFileAndImport() {
      if (!this.selectedFile) {
        this.$message.warning("请先选择一个文件");
        return;
      }
      if (!this.selectedFileHash) {
        this.$message.warning("文件哈希未生成，请稍等");
        return;
      }
      if (this.uploadedFileHashes.includes(this.selectedFileHash)) {
        this.$message.warning("该文件内容已上传过，请勿重复上传");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.selectedFile);
      this.loading = true;

      // 1. 上传文件
      uploadFile(formData)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("文件上传成功");
            this.uploadedFilePath = res.fileName;
            this.uploadedFileHashes.push(this.selectedFileHash);

            // 2. 导入数据
            return this.importDataAndRefresh();
          } else {
            this.$message.error(res.msg || "服务器未返回文件路径");
            this.loading = false;
          }
        })
        .catch((err) => {
          this.$message.error("文件上传失败");
          console.error("上传失败:", err);
          this.loading = false;
        });
    },
    // 导入数据并刷新表格
    importDataAndRefresh() {
      if (!this.uploadedFilePath) {
        this.$message.warning("请先上传文件");
        this.loading = false;
        return;
      }
      if (this.importedFiles.includes(this.uploadedFilePath)) {
        this.$message.warning("该文件已导入过");
        this.loading = false;
        return;
      }

      this.importing = true;

      const backendPath =
        "D:\\ruoyi\\uploadPath\\" +
        this.uploadedFilePath.replace("/profile/", "");

      // 3. 调用导入接口
      importIncomeData({ filePath: backendPath })
        .then((res) => {
          if (res && res.code === 0) {
            this.$message.success("导入成功");
            this.getList(); // 4. 刷新表格

            // 清空文件状态
            this.uploadedFilePath = null;
            this.selectedFile = null;
            this.$refs.uploadRef?.clearFiles();

            this.importedFiles.push(this.uploadedFilePath);
          } else {
            this.$message.error(res.msg || "导入失败");
          }
        })
        .catch((err) => {
          this.$message.error("导入失败");
          console.error("导入失败:", err);
        })
        .finally(() => {
          this.importing = false;
          this.loading = false;
        });
    },
    handlePagination(page) {
      this.queryParams.pageNum = page.page;
      this.queryParams.pageSize = page.limit;
      this.getList();
    },
    disabledDate(time) {
      // Disable current month and future months
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11

      // Disable if selected date is current or future month
      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log("已选行", this.selectedRows);
    },
    // 格式化区县名称（用于表格显示）
    formatDistrictName(district) {
      if (!district) return district;
      const formatted = this.reverseDistrictNameMap[district] || district;
      return formatted;
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        district: "全市",
        gridName: "",
        time: this.getLastMonth(),
      };
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1; // 搜索时重置到第一页
      // 在发送请求前，将显示的区县名称转换为接口需要的参数
      const searchParams = { ...this.queryParams };

      // 处理区县参数
      if (searchParams.district && searchParams.district !== "全市") {
        // 非"全市"情况，进行映射
        searchParams.district =
          this.districtNameMap[searchParams.district] || searchParams.district;
      } else if (searchParams.district === "全市") {
        // "全市"情况，传递特定值给后端（根据后端要求调整）
        searchParams.district = "全市"; // 或者可以尝试传空字符串 "" 或者不传
        // 如果后端需要不同的值表示"全市"，请相应修改
      }

      this.getList(searchParams);
    },
    getList(params) {
      this.loading = true;
      // 如果没有传入参数，则使用this.queryParams
      const searchParams = params || this.queryParams;
      // 打印发送的参数，检查是否包含分页信息
      console.log("发送到接口的参数:", searchParams);

      getSalaryOver50perByMonth(searchParams)
        .then((res) => {
          console.log("原始 res：", res);

          // 修复数据处理逻辑，正确处理分页数据
          let list = [];
          let total = 0;
          
          if (Array.isArray(res)) {
            // 如果直接返回数组（无分页）
            list = res;
            total = res.length;
          } else if (res && typeof res === 'object') {
            // 如果返回的是分页对象
            if (Array.isArray(res.rows)) {
              list = res.rows;
            } else if (Array.isArray(res.data)) {
              list = res.data;
            } else {
              list = [];
            }
            // 获取总记录数
            total = res.total || res.totalCount || list.length;
          } else {
            list = [];
            total = 0;
          }

          console.log("处理后的列表：", list);
          console.log("总记录数：", total);
          console.log("当前页数据量：", list.length);

          this.incomeList = list;
          this.total = res.total || list.length;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取收入数据失败:", error);
          this.loading = false;
          this.$message.error("获取数据失败");
          this.incomeList  = [];
          this.total = 0;
        });
    },
    // 修改handleCountyChange方法（使用简称）
    handleCountyChange(val) {
      console.log("选中的区县：", val);
      this.queryParams.by1 = ""; // 清空网格选择
      if (val) {
        // 直接使用接口返回的简称（如"湖口"）
        getGridName(val)
          .then((res) => {
            // 处理网格数据...
            if (Array.isArray(res)) {
              this.gridOptions = res;
            } else if (res.data && Array.isArray(res.data)) {
              this.gridOptions = res.data;
            } else {
              this.gridOptions = [];
              console.warn("网格数据格式异常:", res);
            }
          })
          .catch((error) => {
            console.error("获取网格失败:", error);
            this.$message.error("获取网格失败");
          });
      } else {
        this.gridOptions = [];
      }
    },
  },
};
</script>

<style scoped>
.test-section {
  border: 1px solid #e1f5fe;
}
</style>
